package com.lyy.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.lyy.security.UserDto;
import com.lyy.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 认证相关的处理
 */
@RestController
@RequestMapping("/authenticate")
public class AuthenticationController {

    private final static ObjectMapper MAPPER=new ObjectMapper();

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 创建token
     * @return
     */
    @PostMapping("/applyToken")
    public JsonNode applyToken(@RequestBody UserDto userDto){
        ObjectNode tokenNode = MAPPER.createObjectNode();
        //1.创建UsernamePasswordAuthenticationToken对象
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(userDto.getUsername(),userDto.getPassword());
        //2.交给认证管理器进行认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if(null!=authenticate){
            //认证成功,生成token返回给前端
            String token = JwtUtils.createToken(userDto.getUsername());
            if(StringUtils.isEmpty(token)){
                tokenNode.put("code","500");
                tokenNode.put("message","生成token失败");
            }else {
                tokenNode.put("code","200");
                tokenNode.put("token", token);
                tokenNode.put("message","success");
            }
            tokenNode.put("code","200");
            tokenNode.put("token", JwtUtils.createToken(userDto.getUsername()));
            tokenNode.put("message","success");
            return tokenNode;
        }else{
            tokenNode.put("code","500");
            tokenNode.put("message","登录失败");
        }
        return tokenNode;
    }
}
